package com.caesar.gxmz;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.caesar.gxmz.adapter.AnimationAdapter;
import com.caesar.gxmz.data.DynamicData;
import com.caesar.gxmz.easypop.CustomerPopUpView;
import com.caesar.gxmz.network.AppNetworkUtils;
import com.caesar.gxmz.network.NetworkCallback;
import com.caesar.gxmz.network.NetworkResultUtils;
import com.caesar.gxmz.network.NetworkUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.dialogplus.DialogPlus;
import com.sch.share.Options;
import com.sch.share.WXShareMultiImageHelper;

import net.tsz.afinal.FinalHttp;

import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.MetaTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static com.caesar.gxmz.network.ApiConfig.FORMALSERVER;
import static com.caesar.gxmz.network.ApiConfig.IMAGE_PATH;

@SuppressLint("JavascriptInterface")
public class DynamicActivity extends Activity {
    private static final String LOG_TAG = "ImageDownloader";
    private ProgressDialog progressDialog = null;
    private WebView webview;
    private LinearLayout rl_titile_bar_right;
    private String shareUrl = null;
    private String dyString = null;
    private List<File> files;
    private Bitmap[] bitmaps;
    private String indexurl = FORMALSERVER;
    private int imageNumber = 0;
    private int fileCount = 0;
    private FinalHttp fh;
    private ImageView btnBack, img_look_up2, img_look_up3;
    private String kDescription = "个秀移动商城";
    private CustomerPopUpView customerPopUpView;
    private int intentType = 0;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            Intent sendIntent = new Intent();
            if (msg.what > 4) {
                sendIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                sendIntent.setType("image/*");
                sendIntent.putExtra(Intent.EXTRA_SUBJECT, kDescription);
                sendIntent
                        .putExtra(Intent.EXTRA_TEXT, kDescription);
                ArrayList<Uri> uris = new ArrayList<Uri>();
                for (File f : files) {
                    Uri uri;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//24
                        uri = FileProvider.getUriForFile(DynamicActivity.this, "com.caesar.gxmz.fileprovider", f);
                        ContentResolver cR = DynamicActivity.this.getContentResolver();
                        if (uri != null && uri.toString().length() > 0) {
                            String fileType = cR.getType(uri);
// 使用 MediaStore 的 content:// 而不是自己 FileProvider 提供的uri，不然有些app无法适配
                            if (fileType.length() > 0) {
                                if (fileType.contains("video/")) {
                                    uri = getVideoContentUri(DynamicActivity.this, f);
                                } else if (fileType.contains("image/")) {
                                    uri = getImageContentUri(DynamicActivity.this, f);
                                } else if (fileType.contains("audio/")) {
                                    uri = getAudioContentUri(DynamicActivity.this, f);
                                }
                            }
                        }
                        Log.d("***uri***", uri.toString());
                    } else {
                        uri = Uri.fromFile(f);
                    }
                    uris.add(uri);
                }
                // 跳转到微信好友群
                sendIntent.putParcelableArrayListExtra(
                        Intent.EXTRA_STREAM, uris);
                // 获取剪贴板管理器：
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label",
                        kDescription);
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
            }
            switch (msg.what) {
                case 1:
                    progressDialog.show();
                    NetworkUtils.fetchInfo( AppNetworkUtils.initHeadersRetrofitApi().getDynamicDetail(dyString),
                            new NetworkCallback<DynamicData>() {
                                @Override
                                public void onSuccess(DynamicData dynamicData) {
                                    if (NetworkResultUtils.successed(dynamicData)) {
                                        DynamicData.DetailData detailData = dynamicData.getData();
                                        if(detailData!=null){
                                            kDescription=detailData.getContent();
                                            List<String> imageUrlList = detailData.getGallary_array();
                                            imageNumber = 0;
                                            fileCount = 0;
                                            String savePath = Environment.getExternalStorageDirectory()
                                                    + File.separator + LOG_TAG + File.separator + "shareImage_"
                                                    + dyString + imageNumber + ".jpg";
                                            File file = new File(savePath);
                                            bitmaps=new Bitmap[imageUrlList.size()];
                                            if(imageUrlList.size() > 0){
                                                // 初始化 ListView 的 adapter 完成在 Android 界面上的显示
                                                for (String ignored : imageUrlList) {
                                                    files.add(file);
                                                }
                                                for (int i = 0; i < imageUrlList.size(); i++) {
                                                    String imageUrl = IMAGE_PATH+imageUrlList.get(i);
                                                    saveImage(imageUrl, i);
                                                }
                                            }
                                        }

                                    }else{
                                        Toast.makeText(DynamicActivity.this, dynamicData.getInfo(), Toast.LENGTH_LONG).show();
                                    }

                                }

                                @Override
                                public void onFailure(Throwable t) {
                                    Toast.makeText(DynamicActivity.this, "网络异常", Toast.LENGTH_LONG).show();
                                }
                            });
                    break;
                case 2:
                    ProcessShareImageTask shareTask2 = new ProcessShareImageTask();
                    shareTask2.execute();
                    break;
                case 3:
                    //一键下载保存到相册
                    for (File f : files) {
                        Intent intent = new Intent(
                                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//24
                            uri = FileProvider.getUriForFile(DynamicActivity.this, "com.caesar.gxmz.fileprovider", f);
                            ContentResolver cR = DynamicActivity.this.getContentResolver();
                            if (uri != null && uri.toString().length() > 0) {
                                String fileType = cR.getType(uri);
// 使用 MediaStore 的 content:// 而不是自己 FileProvider 提供的uri，不然有些app无法适配
                                if (fileType.length() > 0) {
                                    if (fileType.contains("video/")) {
                                        uri = getVideoContentUri(DynamicActivity.this, f);
                                    } else if (fileType.contains("image/")) {
                                        uri = getImageContentUri(DynamicActivity.this, f);
                                    } else if (fileType.contains("audio/")) {
                                        uri = getAudioContentUri(DynamicActivity.this, f);
                                    }
                                }
                            }
                            Log.d("***uri***", uri.toString());
                        } else {
                            uri = Uri.fromFile(f);
                        }
                        intent.setData(uri);
                        DynamicActivity.this.sendBroadcast(intent);
                    }
                    // 跳转到微信朋友圈：最原始的方法（即：下载到相册之后复制文字并跳转到微信界面）不带参数
                    ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    //                         创建普通字符型ClipData
                    ClipData clipData = ClipData.newPlainText("Label", kDescription);
                    //                         将ClipData内容放到系统剪贴板里。
                    clipboardManager.setPrimaryClip(clipData);
                    Toast.makeText(getApplicationContext(), "图片已保存到相册,文字已复制",
                            Toast.LENGTH_SHORT).show();
                    if (intentType == 4) {
                        handler.sendEmptyMessage(4);
                    }
                    break;
                case 4:
                    if (intentType == 4) {
                        Intent wechatIntent = new Intent(Intent.ACTION_MAIN);
                        wechatIntent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI"));
                        wechatIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                        wechatIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(wechatIntent);
                    } else {
                        progressDialog.show();
                        Options options = new Options();
                        options.setOnPrepareOpenWXListener(new Options.OnPrepareOpenWXListener() {
                            @Override
                            public void onPrepareOpenWX() {
                                progressDialog.dismiss();
                            }
                        });
                        options.setText(kDescription);
                        Log.d("getSize=**=>",String.valueOf(bitmaps.length));
                        WXShareMultiImageHelper.shareToTimeline(DynamicActivity.this, bitmaps, options);
                    }
                    break;
                case 5:
                    //带参数跳转到人人相册==>>
                    if (isAppInstalled("com.wuma.teamphoto")) {
                        sendIntent.setPackage("com.wuma.teamphoto");
                        startActivity(sendIntent);
                    } else {
                        ToastUtils.showShort("请安装对应的手机应用");
                    }
                    break;
                case 6:
                    //带参数跳转到微信
                    sendIntent.putExtra("Kdescription", kDescription);
                    sendIntent.setPackage("com.tencent.mm");
                    startActivity(sendIntent);
                    break;
                case 7:
                    //带参数跳转到抖音==>>
                    if (isAppInstalled("com.ss.android.ugc.aweme")) {
                        sendIntent.putExtra("Kdescription", kDescription);
                        sendIntent.setPackage("com.ss.android.ugc.aweme");
                        startActivity(sendIntent);
                    } else {
                        ToastUtils.showShort("请安装对应的手机应用");
                    }
                    break;
                case 8:
                    //带参数跳转到快手
                    if (isAppInstalled("com.smile.gifmaker")) {
                        Intent smileIntent = new Intent(Intent.ACTION_MAIN);
                        smileIntent.setComponent(new ComponentName("com.smile.gifmaker", "com.yxcorp.gifshow.HomeActivity"));
                        smileIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                        smileIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(smileIntent);
                    } else {
                        ToastUtils.showShort("请安装对应的手机应用");
                    }
                    break;
                case 9:
                    //带参数跳转到小红书
                    if (isAppInstalled("com.xingin.xhs")) {
                        Intent redbookIntent = new Intent(Intent.ACTION_MAIN);
                        sendIntent.setComponent(new ComponentName("com.xingin.xhs", "com.xingin.xhs.routers.RouterPageActivity"));
                        redbookIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                        redbookIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(sendIntent);
                    } else {
                        ToastUtils.showShort("请安装对应的手机应用");
                    }
                    break;
                case 10:
                    //带参数跳转到微博==>>
                    if (isAppInstalled("com.sina.weibo")) {
                        sendIntent.setPackage("com.sina.weibo");
                        startActivity(sendIntent);
                    } else {
                        ToastUtils.showShort("请安装对应的手机应用");
                    }
                    break;
                case 11:
                    //带参数跳转到微商相册==>>
                    if (isAppInstalled("com.truedian.dragon")) {
                        sendIntent.putExtra("Kdescription", kDescription);
                        sendIntent.setPackage("com.truedian.dragon");
                        startActivity(sendIntent);
                    } else {
                        ToastUtils.showShort("请安装对应的手机应用");
                    }
                    break;
                case 12:
                    //带参数跳转到微视
                    if (isAppInstalled("com.tencent.weishi")) {
                        sendIntent.setPackage("com.tencent.weishi");
                        startActivity(sendIntent);
                    } else {
                        ToastUtils.showShort("请安装对应的手机应用");
                    }
                    break;
                case 13:
                    progressDialog.dismiss();
                    break;
                default:
                    break;
            }
        }
    };


    /**
     * 判断是否安装了微博
     *
     * @param
     * @return
     */
    public boolean isAppInstalled(String packname) {
        final PackageManager packageManager = getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName.toLowerCase(Locale.ENGLISH);
                if (pn.equals(packname)) {
                    return true;
                }
            }
        }
        return false;

    }

    private Parser htmParser;
    private Parser htmlParser;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);
        if (hasSdcard()) {
            String pathName = Environment.getExternalStorageDirectory()
                    + File.separator + LOG_TAG;
            File file = new File(pathName);
            if (!file.isDirectory()) {
                file.mkdir();
            }
        }
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("请耐心等待...");
        progressDialog.setCancelable(true);
        shareUrl = getIntent().getStringExtra("shareUrl");
        String[] shareArray = shareUrl.split("goods=");
        dyString = shareArray[1];
        webview = (WebView) findViewById(R.id.activity_buy_share_webview);

        rl_titile_bar_right = (LinearLayout) this
                .findViewById(R.id.rl_titile_bar_right);
        img_look_up2 = (ImageView) findViewById(R.id.img_look_up2);
        img_look_up3 = (ImageView) findViewById(R.id.img_look_up3);
        img_look_up2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                handler.sendEmptyMessage(2);
            }
        });
        img_look_up3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
//                AlertDialog.Builder builder = new AlertDialog.Builder(
//                        ShareActivity.this);
//                builder.setTitle("分享:");
//                // 指定下拉列表的显示数据
//                final String[] cities = {"一键下载", "一键转发"};
//                // 设置一个下拉的列表选择项
//                builder.setItems(cities, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        if (which == 0) {
//
//                        } else if (which == 1) {
//
//                        }
//                    }
//                });
//                builder.show();
                customerPopUpView
                        .showAtLocation(img_look_up3, Gravity.BOTTOM, 0, 0);
            }
        });
        // 首页
        btnBack = (ImageView) findViewById(R.id.btnBack);
        btnBack.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                //
                finish();

            }
        });

        // 设置WebView属性，能够执行Javascript脚本
        WebSettings webSettings = webview.getSettings();
        // 设置js可用
        webSettings.setJavaScriptEnabled(true);
        // webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
        webSettings.setSupportZoom(true);
        // webSettings.setBuiltInZoomControls(false);
        // webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        // webSettings.setDomStorageEnabled(true);
        // webSettings.setDatabaseEnabled(true);
        // webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        // 添加js调用接口
        webview.loadUrl(indexurl+"#"+shareUrl);
        files = new ArrayList<File>();
        handler.sendEmptyMessage(1);
        webview.setWebViewClient(new MyWebViewClient());
        initCustomerView();
    }

    private void initCustomerView() {
        customerPopUpView = CustomerPopUpView.create(this);
        customerPopUpView.setOnOkClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (customerPopUpView.isShowing()) {
                    customerPopUpView.dismiss();
                }
                if (adapter instanceof AnimationAdapter) {
                    if (position == 0) {
//                                intentType = 0;//朋友圈
//                                handler.sendEmptyMessage(4);
                        showShareDialog();
                    } else if (position == 1) {
                        intentType = 6;//微信好友群
                        handler.sendEmptyMessage(6);
                    } else if (position == 2) {
                        intentType = 0;//手机相册
                        handler.sendEmptyMessage(3);
                    } else if (position == 3) {
                        intentType = 5;//人人相册
                        handler.sendEmptyMessage(5);
                    }
                } else {
                    switch (position) {
                        case 0:
                            intentType = 7;//抖音
                            handler.sendEmptyMessage(7);
                            break;
                        case 1:
                            intentType = 8;//快手
                            handler.sendEmptyMessage(8);
                            break;
                        case 2:
                            intentType = 9;//小红书
                            handler.sendEmptyMessage(9);
                            break;
                        case 3:
                            intentType = 10;//微博
                            handler.sendEmptyMessage(10);
                            break;
                        case 4:
                            intentType = 11;//微商相册
                            handler.sendEmptyMessage(11);
                            break;
                    }
                }
            }
        });
        customerPopUpView.apply();

    }

    private void showShareDialog() {
        final DialogPlus dialog = DialogPlus.newDialog(this)
                .setGravity(Gravity.CENTER)
                .setContentBackgroundResource(android.R.color.transparent)
                .setContentWidth(ViewGroup.LayoutParams.WRAP_CONTENT)  // or any custom width ie: 300
                .setContentHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
                .setContentHolder(new com.orhanobut.dialogplus.ViewHolder(R.layout.orderconfirm_dialog_layout))
                .setExpanded(false)  // This will enable the expand feature, (similar to android L share dialog)
                .create();
        View holderView = dialog.getHolderView();
        holderView.findViewById(R.id.morder_confirm_btn1).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                intentType = 4;
                handler.sendEmptyMessage(3);
            }
        });
        holderView.findViewById(R.id.morder_confirm_btn2).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                intentType = 0;
                handler.sendEmptyMessage(4);
            }
        });

        dialog.show();
    }

    // Web视图
    private class MyWebViewClient extends WebViewClient {
        @SuppressLint("MissingPermission")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (url.startsWith("tel:")) {
                String[] telNum = url.split("tel:");

                Long num = (long) -1;
                try {
                    num = Long.parseLong(telNum[1]);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    num = (long) -1;
                }

                if (num == -1) {
                    return true;
                }

                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
                        + telNum[1]));
                startActivity(intent);
                return true;
            }
            // view.loadUrl(url);
            return true;
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if(progressDialog.isShowing()){
            progressDialog.dismiss();
        }
    }

    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if(progressDialog.isShowing()){
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(progressDialog.isShowing()){
            progressDialog.dismiss();
        }
    }

    @SuppressLint("NewApi")
    class GetVersionTask extends AsyncTask<String, String, List<String>> {
        private List<String> imageUrlList = new ArrayList<String>();

        @Override
        protected List<String> doInBackground(String... param) {
            try {
                imageUrlList = parserDwPost();
            } catch (ParserException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return imageUrlList;
        }

        @Override
        protected void onPostExecute(List<String> result) {
            imageNumber = 0;
            fileCount = 0;
            String savePath = Environment.getExternalStorageDirectory()
                    + File.separator + LOG_TAG + File.separator + "shareImage_"
                    + dyString + imageNumber + ".jpg";
            File file = new File(savePath);
            bitmaps=new Bitmap[result.size()];
            // 初始化 ListView 的 adapter 完成在 Android 界面上的显示
            if (result != null && result.size() > 0) {
                for (String imageUrl : result) {
                    files.add(file);
                }
                for (int i = 0; i < result.size(); i++) {
                    String imageUrl = result.get(i);
                    saveImage(imageUrl, i);
                }
            }

        }
    }

    private List<String> parserDwPost() throws ParserException {
        ArrayList<String> pTitleList = new ArrayList<String>();
        // 创建 html parser 对象，并指定要访问网页的 URL 和编码格式
        htmParser = new Parser(shareUrl);
        htmParser.setEncoding("utf-8");
        htmlParser = new Parser(shareUrl);
        htmlParser.setEncoding("utf-8");
        String postTitle = "";
        // 获取指定的 div 节点，即 <div> 标签，并且该标签包含有属性 id 值为“tab1”
        NodeList desList = htmParser.extractAllNodesThatMatch(new AndFilter(
                new TagNameFilter("meta"), new HasAttributeFilter("name",
                "Description")));
        kDescription = ((MetaTag) desList.elementAt(0)).getMetaContent();
        NodeList divOfTab1 = htmlParser.extractAllNodesThatMatch(new AndFilter(
                new TagNameFilter("div"), new HasAttributeFilter("class",
                "my-gallery")));

        if (divOfTab1 != null && divOfTab1.size() > 0) {
            // 在 <li> 节点的子节点中获取 Link 节点
            NodeList imageItem = divOfTab1
                    .elementAt(0)
                    .getChildren()
                    .extractAllNodesThatMatch(
                            new NodeClassFilter(ImageTag.class), true);
            for (int i = 0; i < imageItem.size(); ++i) {
                if (imageItem != null && imageItem.size() > 0
                        && pTitleList.size() < 9) {
                    postTitle = ((ImageTag) imageItem.elementAt(i))
                            .getImageURL();
                    System.out.println(postTitle);
                    pTitleList.add(postTitle);
                }

            }

        }
        return pTitleList;
    }

    public boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    private void saveImage(String imageUrl, final int position) {
        String savePath = Environment.getExternalStorageDirectory()
                + File.separator + LOG_TAG + File.separator + "shareImage_"
                + dyString + imageNumber + ".jpg";
        final File file = new File(savePath);
        if (file.exists()) {
            files.set(position, file);
            try {
                FileInputStream fileInputStream=new FileInputStream(file);
                Bitmap bitmap= BitmapFactory.decodeStream(fileInputStream);
                bitmaps[position]=bitmap;
                Log.d("getByteCount=**=>",String.valueOf(bitmap.getByteCount()));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            fileCount++;
            if (fileCount == files.size()) {
                progressDialog.dismiss();
                rl_titile_bar_right.setVisibility(View.VISIBLE);
            }
        } else {
            Glide.with(this)
                    .load(imageUrl)
                    .asBitmap()
                    .toBytes()
                    .into(new SimpleTarget<byte[]>() {
                        @Override
                        public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
                            // 下载成功回调函数
                            // 数据处理方法，保存bytes到文件
                            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                            bitmaps[position]=bitmap;
                            try {
                                InputStream fileInputStream = new ByteArrayInputStream(bytes);
                                FileOutputStream fileOutputStream = new FileOutputStream(file);
                                byte[] buffer = new byte[1024];
                                while (fileInputStream.read(buffer) > 0) {
                                    fileOutputStream.write(buffer);
                                }
                                fileInputStream.close();
                                fileOutputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            files.set(position, file);
                            fileCount++;
                            if (fileCount == imageNumber) {
                                progressDialog.dismiss();
                                rl_titile_bar_right.setVisibility(View.VISIBLE);
                            }
                        }

                        @Override
                        public void onLoadFailed(Exception e, Drawable errorDrawable) {
                            // 下载失败回调
                        }
                    });
//            fh = new FinalHttp();
//
//            fh.download(imageUrl, savePath, new AjaxCallBack<File>() {
//                @Override
//                public void onStart() {
//                    super.onStart();
//                    // Toast.makeText(getApplicationContext(), "开始下载" +
//                    // imageNumber,
//                    // Toast.LENGTH_SHORT).show();
//                }
//
//                @SuppressLint("DefaultLocale")
//                @Override
//                public void onLoading(long count, long current) {
//                    super.onLoading(count, current);
//                }
//
//                @Override
//                public void onSuccess(File t) {
//                    super.onSuccess(t);
//                    // Toast.makeText(getApplicationContext(), "下载完成" +
//                    // imageNumber,
//                    // Toast.LENGTH_SHORT).show();
//                    files.set(position, t);
//                    fileCount++;
//                    if (fileCount == imageNumber) {
//                        progressDialog.dismiss();
//                        rl_titile_bar_right.setVisibility(View.VISIBLE);
//                    }
//                    // Intent intent = new
//                    // Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//                    // Uri uri = Uri.fromFile(t);
//                    // intent.setData(uri);
//                    // ShareActivity.this.sendBroadcast(intent);
//                }
//
//                @Override
//                public void onFailure(Throwable t, String strMsg) {
//                    // TODO Auto-generated method stub
//                    super.onFailure(t, strMsg);
//                    // Toast.makeText(getApplicationContext(), "下载失败" +
//                    // imageNumber,
//                    // Toast.LENGTH_SHORT).show();
//                }
//
//            });
        }
        imageNumber++;
    }

    class ProcessShareImageTask extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... param) {
            Bitmap canMap = null;
            if (files.size() < 4) {
                canMap = Bitmap.createBitmap(600 * files.size(), 600,
                        Bitmap.Config.ARGB_8888);
                for (int i = 0; i < files.size(); i++) {
                    Bitmap bitMap = BitmapFactory.decodeFile(files.get(i)
                            .getAbsolutePath());
                    Canvas canvas = new Canvas(canMap);
                    canvas.drawBitmap(bitMap, i * 600, 0, null);
                }
            } else if (files.size() == 4) {
                canMap = Bitmap.createBitmap(1200, 1200, Bitmap.Config.ARGB_8888);
                for (int i = 0; i < files.size(); i++) {
                    Bitmap bitMap = BitmapFactory.decodeFile(files.get(i)
                            .getAbsolutePath());
                    Canvas canvas = new Canvas(canMap);
                    canvas.drawBitmap(bitMap, i % 2 * 600, i / 2 * 600, null);
                }
            } else if (files.size() > 4 && files.size() < 7) {
                canMap = Bitmap.createBitmap(1800, 1200, Bitmap.Config.ARGB_8888);
                for (int i = 0; i < files.size(); i++) {
                    Bitmap bitMap = BitmapFactory.decodeFile(files.get(i)
                            .getAbsolutePath());
                    Canvas canvas = new Canvas(canMap);
                    canvas.drawBitmap(bitMap, i % 3 * 600, i / 3 * 600, null);
                }
            } else if (files.size() >= 7) {
                canMap = Bitmap.createBitmap(1800, 1800, Bitmap.Config.ARGB_8888);
                for (int i = 0; i < files.size(); i++) {
                    Bitmap bitMap = BitmapFactory.decodeFile(files.get(i)
                            .getAbsolutePath());
                    Canvas canvas = new Canvas(canMap);
                    canvas.drawBitmap(bitMap, i % 3 * 600, i / 3 * 600, null);
                }
            }
            String newPathString = Environment.getExternalStorageDirectory()
                    + File.separator + LOG_TAG + File.separator + "shareImage_"
                    + dyString + "_" + (imageNumber + 1) + ".jpg";

            File file = new File(newPathString);// 将要保存图片的路径
            try {
                BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream(file));
                canMap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return newPathString;
        }

        @Override
        protected void onPostExecute(String result) {
            progressDialog.dismiss();
            if (result != null) {
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                sendIntent.setType("image/*");
                sendIntent.putExtra(Intent.EXTRA_TEXT, kDescription);
//				ComponentName comp = new ComponentName("com.tencent.mm",
//						"com.tencent.mm.ui.tools.ShareImgUI");
                File file = new File(result);// 将要保存图片的路径
                ArrayList<Uri> uris = new ArrayList<Uri>();
//				uris.add(FileProvider.getUriForFile( ShareActivity.this, "com.caesar.gxmz.fileprovider", file ));
                Uri uri;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//24
                    uri = FileProvider.getUriForFile(DynamicActivity.this, "com.caesar.gxmz.fileprovider", file);
                    ContentResolver cR = DynamicActivity.this.getContentResolver();
                    if (uri != null && uri.toString().length() > 0) {
                        String fileType = cR.getType(uri);
// 使用 MediaStore 的 content:// 而不是自己 FileProvider 提供的uri，不然有些app无法适配
                        if (fileType.length() > 0) {
                            if (fileType.contains("video/")) {
                                uri = getVideoContentUri(DynamicActivity.this, file);
                            } else if (fileType.contains("image/")) {
                                uri = getImageContentUri(DynamicActivity.this, file);
                            } else if (fileType.contains("audio/")) {
                                uri = getAudioContentUri(DynamicActivity.this, file);
                            }
                        }
                    }
                    Log.d("***uri***", uri.toString());
                } else {
                    uri = Uri.fromFile(file);
                }
                uris.add(uri);
                sendIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,
                        uris);
//				sendIntent.setComponent(comp);
                sendIntent.addCategory("android.intent.category.DEFAULT");
                sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(sendIntent);
            }
        }

    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param imageFile
     * @return content Uri
     */
    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param videoFile
     * @return content Uri
     */
    public static Uri getVideoContentUri(Context context, File videoFile) {
        String filePath = videoFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Video.Media._ID}, MediaStore.Video.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/video/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (videoFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Video.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param audioFile
     * @return content Uri
     */
    public static Uri getAudioContentUri(Context context, File audioFile) {
        String filePath = audioFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/audio/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (audioFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Audio.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

}
